﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using Fly.Common.WorkFlow;

namespace RN.ERP.Web
{
    public partial class UserMain : BasePage
    {
        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        private BasicService.BasicServiceClient basicServiceClient = new BasicService.BasicServiceClient();
        public string CorpUserGuid = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                BindData();
                GetEmpCounts();
                CheckEmbarnchMent();
                BindMarket();
            }
        }

        private void BindData()
        {
            if (AppID == "101")
            {
                litTitle.Text = "申报证书总览";
            }
            else
            {
                litTitle.Text = "申报人数总览";
            }
            CorpUserGuid = UserInfo.CorpUserGuid;
            ltrLoginUser.Text = UserInfo.UserName;
            ////获取单位信息
            QueryCompanyInfoCondition queryCompanyInfoCondition =
                new QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(UserInfo.CorpUserGuid), O = OptEnum.Equal } };
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            var jcorp = enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea);
            var corpInfo = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(jcorp);
            ltrCorpAddress.Text = corpInfo.Address;
            ltrCorpName.Text = corpInfo.CorpName;
            ltrCorpRegisterMoney.Text = corpInfo.RegisterMoney;
            ltrLoginCorpName.Text = corpInfo.CorpName;
            ltrLoginCorpRegisterArea.Text = basicServiceClient.GetAddress(corpInfo.AreaCode);
            string app = Application[ApplicationConstant.APPLICATION_CORPUSERTYPE] != null ? Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString() : "";
            Dictionary<string, string> CorpTypeDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(app);
            var roleId = GetRoleIdByClassId(corpInfo.classID.ToString());
            ltrLoginCorpType.Text = CorpTypeDic.ContainsKey(roleId) ? CorpTypeDic[roleId] : "";

            ////获取资质信息
            BindQualityInfo();
            ucMarketInfo.CorpUserGuid = CorpUserGuid;
            string roleid = UserInfo.RoleId;
            string currentAreaCode = UserInfo.CurrentArea;
            var flowResult = basicServiceClient.GetNextFlowCode(roleid, "", currentAreaCode, corpInfo.classID.ToString(), GetEmbranchmentFlow(currentAreaCode), BasicService.OptType.Edit);
            var nextFlowNode = JsonConvert.DeserializeObject<FlowResult>(flowResult);
            if (!nextFlowNode.Result)//if (nextFlowNode != null && !nextFlowNode.Result)
            {
                this.btnPost.Disabled = true;
                btnPost.Visible = false;
            }
            else
            {
                btnPost.Disabled = false;
                btnPost.Visible = true;
            }
        }

        public string GetAreaTitle(object areaCode)
        {
            string title = "";
            if (areaCode != null)
            {
                string code = areaCode.ToString();
                if (code.Length >= 2)
                {
                    var areaInfos = JsonConvert.DeserializeObject<List<a_AreaInfo>>(Application[ApplicationConstant.APPLICATION_AREA].ToString());
                    var currentArea = areaInfos.Where(a => code.StartsWith(a.Code)).FirstOrDefault();
                    title = currentArea == null ? "" : currentArea.Title;
                }
            }
            return title;
        }

        public string GetSubAreaTitle(object areaCode)
        {

            string title = "";
            if (areaCode != null)
            {
                string code = areaCode.ToString();
                if (code.Length > 2)
                {
                    var subAreaInfos = JsonConvert.DeserializeObject<List<ModelService.a_AreaSubInfo>>(basicServiceClient.GetQu(code.Substring(0, 2)));
                    var currentSubArea = subAreaInfos.Where(a => a.SortCode == areaCode).FirstOrDefault();
                    title = currentSubArea == null ? "" : currentSubArea.Title;
                }
            }
            return title;
        }

        public void BindMarket()
        {
            QueryCompanyInfoCondition queryCompanyInfoCondition =
           new QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(UserInfo.CorpUserGuid), O = OptEnum.Equal } };
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            var jcorp = enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea);
            var corpInfo = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(jcorp);
            if (corpInfo == null)
            {
                return;
            }
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), UserInfo.CurrentArea));
            string flowCode = string.Empty;
            if (flow != null)
            {
                flowCode = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            ltrCurrentMarketFlow.Text = basicServiceClient.GetFlowCodeTitle(UserInfo.CurrentArea, corpInfo.classID.ToString(), flowCode);
        }

        public string GetEmbranchmentFlow(object areaCode)
        {
            string flowTitle = "";
            if (areaCode == null)
            {
                return flowTitle;
            }
            string code = areaCode.ToString();
            Tb_Corp_CompanyInfo corpInfo = new Tb_Corp_CompanyInfo();
            corpInfo.CorpUserGuid = Guid.Parse(UserInfo.CorpUserGuid);
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), code));
            if (flow != null)
            {
                flowTitle = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            return flowTitle;
        }

        private void BindQualityInfo()
        {
            List<QueryCorpQualityInfoCondition> queryQualityList = new List<QueryCorpQualityInfoCondition>() { new QueryCorpQualityInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(UserInfo.CorpUserGuid), O = OptEnum.Equal } } };
            var queryCondition = JsonConvert.SerializeObject(queryQualityList);
            string currentAreaCode = UserInfo.CurrentArea;
            var qualities = JsonConvert.DeserializeObject<List<tb_Corp_Quality>>(enterpriseServiceClient.GetCompanyQualities(UserInfo.CorpUserGuid, queryCondition, currentAreaCode));
            RadGridCorpQuals.DataSource = qualities;
            RadGridCorpQuals.DataBind();
        }
        /// <summary>
        /// 企业工作人员
        /// </summary>
        private void GetEmpCounts()
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                RepEmpCount.DataSource = JsonConvert.DeserializeObject<List<ModelService.KeyValue>>(client.GetEmpCounts(UserInfo.CorpUserGuid, UserInfo.AreaCode));
                RepEmpCount.DataBind();
            }
        }

        private void CheckEmbarnchMent()
        {
            string corpUserGuid = string.Empty;
            if (!string.IsNullOrEmpty(Request["corpUserGuid"]))
            {
                corpUserGuid = Request["corpUserGuid"];
            }
            if (string.IsNullOrEmpty(corpUserGuid))
            {
                corpUserGuid = UserInfo.CorpUserGuid;
            }
            Tb_Corp_CompanyInfo corp = new Tb_Corp_CompanyInfo();
            Guid guid = Guid.Empty;
            if (Guid.TryParse(corpUserGuid, out guid))
            {
                corp.CorpUserGuid = guid;
                var Embranchments = enterpriseServiceClient.GetCorpEmbranchments(JsonConvert.SerializeObject(corp));
                var CorpEmbranchments = JsonConvert.DeserializeObject<IList<Tb_Corp_Embranchment>>(Embranchments);
                if (CorpEmbranchments != null && CorpEmbranchments.Count > 0)
                {
                    ////未在省内确定市场范围
                    hdnEmbranchMentCount.Value = CorpEmbranchments.Count.ToString();
                }
            }
        }

        private string GetRoleIdByClassId(string classID)
        {
            var roleClassIds = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetDictionary("RoleClassId", "", ""));
            var curRoleClass = roleClassIds.FirstOrDefault(r => r.Value == classID);
            if (!string.IsNullOrEmpty(curRoleClass.Key))
            {
                return curRoleClass.Key;
            }
            return "";
        }

    }
}
